<?php

namespace App\Console\Commands;

use App\Models\BankCard;
use App\Models\Order;
use App\Models\OrderLease;
use App\Models\OtherWithholdLog;
use App\Models\ShopSms;
use App\Models\YifubaoPay;
use App\Services\AlipayService;
use App\Services\ChargeService;
use App\Services\CommonService;
use App\Services\CreditCallService;
use App\Services\EsignService;
use App\Services\GoodsService;
use App\Services\OrderService;
use App\Services\SuningPayService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class YifubaoPayOrderLeaseCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'yifubaoPayOrderLease';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '订单账单到期易付宝扣款付款';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    protected function handleExec()
    {
       $this->yifubaoPayOrderLease();
    }

    const TIME_LIMIT = 3; //单位小时
    const ORDER_NUM_LIMIT = 50; //一次操作订单数量
    const NOT_HANDEL_SHOP = [

    ];

    /**
     * 签约未支付订单分期账单到期易付宝扣款付款
     */
    public function yifubaoPayOrderLease(){
        try {

            $leaseStatus = [
                OrderLease::ORDER_LEASE_STATUS_NOPAY,
                OrderLease::ORDER_LEASE_STATUS_OVERDUE,
            ];
            $where = [
                ['o.pay_type','!=',Order::ORDER_PAY_TYPE_HUABEI],
                ['ol.withhold_status',OrderLease::LEASE_WITHHOLD_STATUS_NO],
                ['ol.begin_time','<=',strtotime(date('Y-m-d 23:59:59',strtotime('-1 day')))],
                ['m.openId','!=',''],
                ['o.create_time','<',1713456000],
            ];
            //数据
            $dataArr = Order::from('sp_order_2 as o')
                ->select('o.id','o.status as order_status','o.trade_no','ol.id as lease_id','ol.begin_time','ol.status as lease_status','o.uid','m.openId')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id','ol.order_id')
                ->leftjoin('sp_member_2 as m', 'o.uid','m.id')
                ->whereIn('o.status',OrderService::getOrderStatus(OrderService::ORDER_OVERDUE_COUNT))
                ->whereIn('ol.status',$leaseStatus)
                ->where($where)
                ->orderBy('ol.id', 'asc')
                ->get();
            $dataArr = obToArray($dataArr);
//            return   $this->infoLog('订单分期账单到期易付宝扣款付款执行成功',$dataArr);

            if($dataArr){
                foreach ($dataArr as $k=>$order){
                    $OrderLease= OrderLease::where('id',$order['lease_id'])->where('order_id',$order['id'])
                        ->select(
                            'id','which_period','rent','status','paid_rent'
                        )
                        ->first();
                    $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
                    if(empty($OrderLease)||($OrderLease['status']==1&&!empty($OrderLease['pay_time']))){
                       continue;
                    }

                    $userBank=BankCard::where('uid',$order['uid'])->get()->toArray();
                    if(empty($userBank)){
                        continue;
                    }
                    $ispay=0;
                   foreach($userBank as $bres){
                       if($ispay){
                           continue;
                       }
                       $leaseId=$OrderLease['id'];
//                       $data['notifyUrl'] = config('alipay.callbackDomain');
                       $data['contractNo']=$bres['contract_no'];//'202307267881357'
                       $data['goodsName']='主动支付'.$order['trade_no'];
                       $data['orderAmount']=sprintf('%.2f',bcsub($OrderLease['rent'],$OrderLease['paid_rent'],2));
                       $data['orderName']=base64_encode('易付宝自动扣款支付第'.$OrderLease['which_period'].'期');
                       $data['outOrderNo']=$order['id'].rand(1000,9999).time();
                       $result=SuningPayService::agreementPaymentPay($data);//银行卡协议支付
                       if($result['statusCode']=='S'){
                           DB::beginTransaction();
                           //添加记录
                           $insertData = [
                               'trans_id'=>$data['outOrderNo'],
                               'order_id'=>$order['id'],
                               'trade_no'=>$order['trade_no'],
                               'lease_id'=>$OrderLease['id'],
                               'which_period'=>$OrderLease['which_period'],
                               'txn_amt'=>$data['orderAmount'],
                               'create_time'=>date('Y-m-d H:i:s'),
                               'update_time'=>date('Y-m-d H:i:s'),
                               'is_pay'=>YifubaoPay::PAY_YES
                           ];
                           YifubaoPay::insert($insertData);

                           $leaseSave['trade_no']   = $order['trade_no'];
                           $leaseSave['out_order_no'] = $data['outOrderNo'];
                           $leaseSave['pay_time']  = time();
                           $leaseSave['status']    = OrderLease::ORDER_LEASE_STATUS_PAID;
                           $leaseSave['pay_type'] = OrderLease::PAY_TYPE_YIFUBAO;
                           $leaseSave['paid_rent']     = $OrderLease['rent'];

                           if($OrderLease['which_period'] == 1){
                               if($order['is_renewal'] == Order::ORDER_NOT_RENEWAL){
                                   if($order['is_skip'] == Order::RISK_SKIP_YES){
                                       $arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                                   }else{
                                       $risk_res = ChargeService::RiskCreditUse($order['seller_id'],$order['id'],$order['cert_name'],$order['cert_no'],$order['mobile'],1);
                                       $arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                                   }
                                   $user_order_count = Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->sum('amount');
                                   Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->update(['user_order_count'=>$user_order_count]);
                               }else{//续租订单不发货，第一期扣款成功订单状态直接变为租用中
                                   if(OrderLease::where([['order_id',$order['id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->count() == $order['month_total']){
                                       $arr['status'] = OrderService::ORDER_STATUS_TOBE_RETURNED;
                                   }else{
                                       $arr['status'] = OrderService::ORDER_STATUS_CONFIRM_GOODS;
                                   }
                               }
                               Order::where(['id' => $order['id']])->update($arr);
                               //短信通知
                               ShopSms::orderPlaceSendToShop($order['seller_id'],$order['realname'],$order['trade_no']);
                               ShopSms::orderPaidSendToUser($order['seller_id'],$order['realname'],$order['trade_no'],$OrderLease['rent'],$order['mobile'],$order['id']);
                           }

                           //更改已还租期
                           Order::where(['id' => $order['id']])->increment('month_paid',1);
                           $resulta=OrderLease::where('id',$leaseId)->update($leaseSave);
                           if($resulta){
                               DB::commit();
                           }else{
                               DB::rollBack();
                           }

                           OtherWithholdLog::orderWithholdLog($order['trade_no'],$leaseId,$data['outOrderNo'],$order['trade_no'],$result,OtherWithholdLog::PAY_TYPE_YIFUBAO,true,1);
                           //检测逾期订单状态
                           if($status = Order::checkOrderOverdueStatus($order['id'])){
                               Order::where(['id' => $order['id']])->update(['status'=>$status]);
                           }
                           $ispay=1;
                           CreditCallService::repayInvestData($order['id'],$leaseId);//上报征信-还款
                       }else{
                           OtherWithholdLog::orderWithholdLog($order['trade_no'],$leaseId,'',$order['trade_no'],$result,OtherWithholdLog::PAY_TYPE_YIFUBAO,false,1);
                       }
                   }
                }

            $this->infoLog('订单分期账单到期易付宝扣款付款执行成功',$dataArr);
            }
        }catch (\Exception $exception){
            $this->infoLog('订单分期账单到期易付宝扣款付款执行失败'.$exception->getMessage());
        }
    }
}
